﻿using AutoMapper;
using MediatR;
using System.Diagnostics;
using TaskProject.Application.Command.Production;
using TaskProject.Domain.Production;
using TaskProject.ErrorCode;
using TaskProject.InfrasIntructure.Implement;

namespace TaskProject.Application.Handler.Production
{
    public class AddReportWrokHandler : IRequestHandler<AddReportWrokCommand, APIResult<int>>
    {
        DatabaseContext db;
       
        public AddReportWrokHandler(DatabaseContext db)
        {
            this.db = db;
           
        }

        public async Task<APIResult<int>> Handle(AddReportWrokCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> res = new APIResult<int>();

            // 1. 根据ProcessId获取工序信息
            var process = await db.sqlSugar.Queryable<ProductProcessModel>()
                .Where(p => p.ProcessId == request.ProcessId)
                .FirstAsync(cancellationToken);

            if (process == null)
            {
                res.Code = APIEnum.Fail;
                res.Msg = "工序不存在";
                return res;
            }

            // 2. 根据Order字段的值决定创建几个人的报工记录
            int numberOfPeople = process.Order; // Order是多少就需要几个人

            if (numberOfPeople > 1)
            {
               
                var personNames = new List<string>();
                for (int i = 1; i <= numberOfPeople; i++)
                {
                    personNames.Add($"人员{i}");
                }

                
                var reportWorks = new List<ReportWorkModel>();
                foreach (var personName in personNames)
                {
                    var reportWork = new ReportWorkModel
                    {
                        ProcessId = request.ProcessId,
                        ReportQuantity = request.ReportQuantity,
                        Name = personName
                    };
                    reportWorks.Add(reportWork);
                }

                // 批量插入
                var insertResult = await db.sqlSugar.Insertable(reportWorks).ExecuteCommandAsync();
                res.Data = insertResult;
                res.Msg = $"成功为{insertResult}个人报工";
            }
            else if (numberOfPeople == 1)
            {
                // 单个人报工
                var reportWork = new ReportWorkModel
                {
                    ProcessId = request.ProcessId,
                    ReportQuantity = request.ReportQuantity,
                    Name = request.Name // 使用传入的人员名称
                };

                var insertResult = await db.sqlSugar.Insertable(reportWork).ExecuteCommandAsync();
                res.Data = insertResult;
                res.Msg = "报工成功";
            }
            else
            {
                // Order为0或负数的情况
                res.Code = APIEnum.Fail;
                res.Msg = "加工顺序无效";
            }

            return res;
        }
    }
}
